大家好~
今天要開始實作留言功能,
個人習慣先從建立 Model 開始,
在建立 Model 時,
指令可以帶上不同參數,
可以一起生成其他所需檔案。
使用 make:model 可以快速創建 Model class。
php artisan make:modle ModelName
帶上不同參數可以建立其他相關 class。
以下生成指令節錄至 Laravel 官方文件。
# Generate a model and a database migration...
php artisan make:model Flight --migration
php artisan make:model Flight -m
# Generate a model and a FlightFactory class...
php artisan make:model Flight --factory
php artisan make:model Flight -f
# Generate a model and a FlightSeeder class...
php artisan make:model Flight --seed
php artisan make:model Flight -s
# Generate a model and a FlightController class...
php artisan make:model Flight --controller
php artisan make:model Flight -c
# Generate a model and a migration, factory, seeder, and controller...
php artisan make:model Flight -mfsc
# Shortcut to generate a model, migration, factory, seeder, and controller...
php artisan make:model Flight --all
# Generate a pivot model...
php artisan make:model Member --pivot
至於本專案目前預計會用到的只有 Controller 與 Migration,
所以指令的部分我們只要帶上 -cm 就可以了~
php artisan make:model Message -cm

成功後會建立以下三個檔案:
Migration 內會有兩個 function,
分別是 up() 與 down();up():執行 php artisan migrate 時會執行的部分。down():執行 php artisan migrate:rollback 時會執行的部分。
public function up()
{
    Schema::create('messages', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id');
        $table->string('title');
        $table->string('content');
        $table->timestamps();
    });
}
使用 php artisan migrate 執行 migration
php artisan migrate

執行完指令後,
就可以看到我們的資料表已經生成囉。

Laravel 的 Migration 提供許多的 Available Column Types 與 Column Modifiers 可以使用,
使用方式也很簡單~
接下來要把 Model 加上關聯關係。
一位 User 可以有多則 Messages,
一則 Message 只能屬於一位 User 發布的。
來建立 Model 的一對多關聯關係吧!
public function messages()
{
    return $this->hasMany(Message::class);
}
public function user()
{
    return $this->belongsTo(User::class);
}
這樣關聯關係就建立好了。
Eloquent 會將所屬 Model 名稱轉成 Snake Case 形式,
再加上 _id 後綴作為外鍵名稱。
以上面的關聯關係為例,
Eloquent 就會使用 user_id 當作外鍵名稱。
下圖是節錄至 src/Illuminate/Database/Eloquent/Model.php 中取得外鍵名稱的部分,
有興趣的可以看看~

使用 create( ) 建立資料時,
如果沒在 Model 指定 fillable 或 guarded 其中一種屬性的話,
我們的 Model 就無法進行批量賦值喔。
protected $fillable=[
    'title',
    'content'
];
在 app/Models/Message.php 內,
使用 $fillable 允許 title 與 content 可以被批量賦值。
資料庫建好了,
關聯關係也用好了,
明天就開始來做 CRUD 吧!
大家明天見啦~
若文章有任何問題,
還請大家不吝賜教!